/*
 * Copyright 2010 - 2011, The PLDesktop Development Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#ifndef PLPIC_H
#define PLPIC_H

#include <machine/pc/processor/irqmanager.h>
#include <machine/pc/ioport.h>
#include <lib/kvector.h>

#include <tools/PLSingleton.h>
using namespace PLSDK;

/**
 * The x86/x64 programmable interrupt controller as IrqManager.
 */
class PLPic : public PLSingleton<PLPic>, public PLIrqManager, private InterruptHandler {
	friend class PLSingleton<PLPic>;
public:
	/**
	 * Start the controler.
	 *
	 * @return True if the start was successfully.
	 */
	bool start();
	/**
	 * Register an ISA irq.
	 *
	 * @param irq the ISA irq number (from 0 to 15).
	 * @param handler pointer to the IrqHandler class.
	 * @param bEdge whether this IRQ is edge triggered or not.
	 * @return the irq's identifier.
	 */
	virtual uint32_t registerIsaIrqHandler(uint8_t irq, PLIrqHandler *handler, bool bEdge = false);
	/**
	 * Acknoledge the IRQ reception, in case you returned false in the PLIrqHandler::irq() function. If
	 * this is not called there won't be any following irqs.
	 *
	 * @param Id the irq's identifier.
	 */
	virtual void acknowledgeIrq(uint32_t Id);
	/**
	 * Unregister a previously registered IrqHandler.
	 *
	 * @param Id the irq's identifier.
	 * @param handler pointer to the handler class.
	 */
	virtual void unregisterHandler(uint32_t Id, PLIrqHandler *handler);
protected:
	/**
	 * Constructor.
	 */
	PLPic();
private:
	inline virtual ~PLPic() {}
	PLPic(const PLPic &);
	PLPic &operator = (const PLPic &);
	virtual bool interrupt(size_t nInterruptNumber, InterruptState &state);
	void eoi(uint8_t irq);
	virtual void enable(uint8_t irq, bool enable);
	void enableAll(bool enable);
	PLIOPort m_SlavePort;
	PLIOPort m_MasterPort;
	PLKVector<PLIrqHandler *> m_Handler[16];
	bool m_HandlerEdge[16];
};

#endif
